<?php 
require_once "core/init.php";

$user = new User();

if (!$user->isLoggedIn()) {
	Redirect::to('index.php');
}

if (Input::exists()) {
	if (Token::check(Input::get('token'))) {
		//echo "has token";

		$validate = new Validation();
		$validation = $validate->check($_POST, array(
			'current_password' => array(
				'required' => true,
				 'min' => 6
			),
			'password_new' => array(
				'required' => true,
				 'min' => 6
			),
			'password_new_again' => array(
				'required' => true,
				 'min' => 6,
				 'matches' => 'password_new'
			)

		));

		if($validation->passed()){
			//change password

			if (Hash::make(Input::get('current_password'), $user->data()->salt) !==  $user->data()->password) {
				//echo "Incorrect current password";
			}else{
				//echo "ok";
				$salt = Hash::salt(32);
				$user->update(array(
					'password' => Hash::make(Input::get('password_new'), $salt),
					'salt' => $salt
				));
				Session::flash('home', 'Your password has been change');
				Redirect::to('index.php');
			}

		}else {
			foreach ($validation->errors() as $error) {
				echo $error . "<br/>";
			}
		}

	}
}

?>

<form action="" method="post">

	<div class="field">
		<label for="current_password">Current Password</label>
		<input type="password" name="current_password" id="current_password" value="" autocomplete="off">
	</div>

	<div class="field">
		<label for="password">Password new</label>
		<input type="password" name="password_new" id="password_new" value="" autocomplete="off">
	</div>

	<div class="field">
		<label for="password_new_again"> Re-type new  Password</label>
		<input type="password" name="password_new_again" id="password_new_again" value="" autocomplete="off">
	</div>

	<div class="field">
		<input type="submit" value="Update password">
	</div>

	<div class="field">
		<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
	</div>
</form>